/* trackuino-aprs copyright (C) 2012  OA4AJP Alfredo Mendiola
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "config.h"
#include "radio_mx145_spi.h"
#include <SPI.h>
#include <WProgram.h>

const int MAX_RES = 16;
const int MIN_RES = 1;
char response[MAX_RES];

void RadioMx145Spi::send_cmd(const char *cmd, int cmd_len, char *resp, int res_len)
{
  byte r;
  int i,j;
  
  SPI.begin ();  // Join the SPIbus as a master
  SPI.setDataMode(SPI_MODE0); 
  SPI.setClockDivider(SPI_CLOCK_DIV128); //125khz  
  
  // enable Slave Select
  digitalWrite(SS_PIN, LOW);    // SS is pin 10		  
  
  for (i = 0; i < cmd_len; i++) {
	SPI.transfer(cmd[i]);
  }
  // disable Slave Select
  digitalWrite(SS_PIN, HIGH);
  delay(100);

  /*
  //Response code

  // enable Slave Select  
  digitalWrite(SS_PIN, LOW);    // SS is pin 10	
  
  r = SPI.transfer(0x3F); // Dummy "?"
  delayMicroseconds (20);	

  // disable Slave Select
  digitalWrite(SS_PIN, HIGH);	


  if (res_len > 0) {
    for (j = 0; j < res_len; j++) {	  
      resp[j] = r;
	  Serial.println(r, HEX);
    }
  }
  */
  // turn SPI hardware off
  SPI.end ();   
}

void RadioMx145Spi::set_freq(unsigned long freq)
{
  char cmd[5];
  cmd[0] = 'B';
  *((unsigned long *)(cmd+1)) = freq;
  memset(response, 0, sizeof(response));
  send_cmd(cmd, 5, response, MIN_RES);
  
  //This print the MISO line response, just if it is connected to the mx145/146 Modules!!!!
  //Serial.print("Error code: ");
  //Serial.println(response[0], HEX); 
}

void RadioMx145Spi::setup()
{ 
  //Delay to wait the Mx146 to Power On
  delay(100);
  set_freq(MX145_FREQUENCY);    
}

void RadioMx145Spi::ptt_on()
{
  digitalWrite(PTT_PIN, HIGH);
  delay(50); //Don't reduce this value
}

void RadioMx145Spi::ptt_off()
{
  digitalWrite(PTT_PIN, LOW);
}
